<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 搜索与添加区域 -->
        <el-row :gutter="0">
          <el-col>
            <!-- 提示信息 -->
            <el-alert
              style="margin-bottom:15px"
              title="提示：只允许为第三级分类设置参数"
              type="warning"
              :show-icon="true"
            ></el-alert>
          </el-col>
          <el-col>
            <span>选择商品分类：</span>
            <!-- options 绑定数据源 -->
            <!-- props 绑定配置对象 -->
            <el-cascader
              placeholder="试试搜索"
              expand-trigger="hover"
              :options="productsTypeList"
              :props="cascaderProps"
              v-model="selectedIds"
              :filterable="true"
              :clearable="true"
              :change-on-select="true"
              @change="cascaderChanged"
            ></el-cascader>
          </el-col>
        </el-row>

        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="动态参数" name="1">
            <el-button
              type="primary"
              size="mini"
              :disabled="isBtnDisable"
              @click="dialogVisibleAdd=true"
            >添加参数</el-button>
            <!-- 动态参数表格数据 -->
            <el-table :data="dynamicTableData" :border="false" :stripe="true">
              <el-table-column type="expand">
                <template slot-scope="{row}">
                  <el-tag
                    :key="i"
                    v-for="(tag,i) in row.values"
                    :closable="true"
                    :disable-transitions="false"
                    @close="handleClose(i, row)"
                  >{{tag}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="row.inputTagVisible"
                    v-model="row.inputTagValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(row)"
                    @blur="handleInputConfirm(row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数名称" prop="name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="{row}">
                  <!-- 修改 -->
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    circle
                    size="mini"
                    @click="dialogVisibleEditShow(row.id)"
                  ></el-button>

                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    size="mini"
                    @click="deleteById(row.id)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="2">
            <el-button
              type="primary"
              size="mini"
              :disabled="isBtnDisable"
              @click="dialogVisibleAdd=true"
            >添加属性</el-button>
            <!-- 静态属性表格数据 -->
            <el-table :data="staticTableData" :border="false" :stripe="true">
              <el-table-column type="expand">
                <template slot-scope="{row}">
                  <el-tag
                    :key="i"
                    v-for="(tag,i) in row.values"
                    :closable="true"
                    :disable-transitions="false"
                    @close="handleClose(i, row)"
                  >{{tag}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="row.inputTagVisible"
                    v-model="row.inputTagValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(row)"
                    @blur="handleInputConfirm(row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="属性名称" prop="name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="{row}">
                  <!-- 修改 -->
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    circle
                    size="mini"
                    @click="dialogVisibleEditShow(row.id)"
                  ></el-button>

                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    size="mini"
                    @click="deleteById(row.id)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + dialogTitleText"
      :visible.sync="dialogVisibleAdd"
      width="50%"
      @close="dialogVisibleAddColsed"
    >
      <el-form :model="addFormData" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="dialogTitleText" prop="name">
          <el-input v-model="addFormData.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="addFormOp">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改'+dialogTitleText"
      :visible.sync="dialogVisibleEdit"
      width="50%"
      @close="dialogVisibleEditColsed"
    >
      <el-form :model="editFormData" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="dialogTitleText" prop="name">
          <el-input v-model="editFormData.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="editFormOp">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      dialogVisibleAdd: false,
      dialogVisibleEdit: false,
      productsTypeList: [],
      // 级联选择器的绑定配置对象
      cascaderProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: false,
      },
      // 级联选择器选中双向绑定的数组
      selectedIds: [],
      // 被激活的标签页名称
      activeName: '1',
      // 动态属性
      dynamicTableData: [],
      // 静态属性
      staticTableData: [],
      addFormData: {
        name: '',
      },
      addFormRules: {
        name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      },
      editFormData: {},
      editFormRules: {
        name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getProductsTypeList()
  },
  methods: {
    dialogVisibleAddShow() {
      this.dialogVisibleAdd = true
    },
    async dialogVisibleEditShow(id) {
      await this.$http
        .get(`/productsType/${this.selectedId}/attributes/${id}`, {
          params: { selectedtype: this.activeName },
        })
        .then((res) => {
          res = res.data
          // console.log(res)
          if (res.code !== 1) return this.$message.error(res.msg || '获取失败')

          this.editFormData = res.data
          // console.log(this.editFormData)
          this.dialogVisibleEdit = true
        })
        .catch((err) => {
          this.$message.info('已取消删除' || err.message)
        })
    },
    async deleteById(id) {
      const confirm = await this.$confirm(
        '此操作将删除该数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirm !== 'confirm' || confirm === 'cancel') {
        return this.$message.info(window.defineGlobalConstData.delCancel)
      }

      // console.log(id)
      await this.$http
        .delete(`/productsType/${this.selectedId}/attributes/${id}`)
        .then((res) => {
          res = res.data
          // console.log(res)
          if (!res.code || res.code == 0)
            return this.$message.error(
              res.msg || window.defineGlobalConstData.opError
            )

          this.$message.success(
            res.msg || window.defineGlobalConstData.opSuccess
          )
          this.getParamsData()
        })
        .catch((err) => {
          this.$message.error(
            err.message || window.defineGlobalConstData.opError
          )
        })
    },
    // 删除为空的子节点
    deleteEmptyChildren(obj) {
      // console.log(obj)
      function traversal(data) {
        for (var item of data) {
          if (item.children) {
            if (item.children.length > 0) {
              traversal(item.children)
            }
            if (item.children.length === 0) {
              delete item.children
            }
          }
        }
      }

      traversal(obj)
    },
    // 获取商品类型
    async getProductsTypeList() {
      await this.$http
        .get('/productsType', {
          params: { type: 2 },
        })
        .then((res) => {
          res = res.data
          // console.log(res)
          if (!res.code || res.code == 0)
            return this.$message.error(res.msg || '获取数据失败')

          this.productsTypeList = res.data.list

          this.deleteEmptyChildren(this.productsTypeList)
        })
        .catch((err) => {
          return this.$message.error(err.message || '获取失败')
        })
    },
    // 级联选择器选中数据变化触发
    cascaderChanged() {
      // console.log(this.selectedIds)
      this.getParamsData()
    },
    // 处理标签页点击事件的处理函数
    handleTabClick() {
      this.getParamsData()
    },
    // 获取产品分类参数列表
    async getParamsData() {
      // 选中的不是 3 级分类直接清空选中并返回
      if (this.selectedIds.length !== 3) {
        this.selectedIds = []
        this.dynamicTableData = []
        this.staticTableData = []
        return
      }

      // 选中的是三级分类，根据所选的分类 ID，和当前所处的面板获取对应的参数
      await this.$http
        .get(`/productsType/${this.selectedId}/attributes`, {
          params: { selectedtype: this.activeName },
        })
        .then((res) => {
          res = res.data
          // console.log(res)
          if (!res.code || res.code == 0)
            return this.$message.error(res.msg || '获取数据失败')

          res.data.forEach((item) => {
            item.values = item.values ? item.values.split(',') : []
            // 新增属性控制文本框显示与隐藏
            item.inputTagVisible = false
            item.inputTagValue = ''
          })

          if (this.activeName === '1') {
            this.dynamicTableData = res.data
          } else {
            this.staticTableData = res.data
          }
        })
        .catch((err) => {
          return this.$message.error(err.message || '获取失败')
        })
    },
    addFormOp() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return

        await this.$http
          .post(`/productsType/${this.selectedId}/attributes`, {
            name: this.addFormData.name,
            selectedtype: this.activeName,
            values: '',
          })
          .then((res) => {
            res = res.data
            if (!res.code || res.code == 0)
              return this.$message.error(res.msg || '操作失败')

            this.$message.success(res.msg || '操作成功')
            this.dialogVisibleAdd = false
            this.getParamsData()
          })
          .catch((err) => {
            return this.$message.error(err.message)
          })
      })
    },
    // 监听添加对话框的关闭事件
    dialogVisibleAddColsed() {
      this.$refs.addFormRef.resetFields()
    },
    // 监听添加对话框的关闭事件
    dialogVisibleEditColsed() {
      this.$refs.editFormRef.resetFields()
    },
    editFormOp() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        await this.$http
          .put(
            `/productsType/${this.selectedId}/attributes/${this.editFormData.type_id}`,
            {
              params: {
                name: this.editFormData.name,
                selectedtype: this.activeName,
                values: this.editFormData.value,
              },
            }
          )
          .then((res) => {
            res = res.data
            // console.log(res)
            if (!res.code || res.code == 0)
              return this.$message.error(res.msg || '操作失败')

            this.$message.success('操作成功')
            this.getParamsData()
            this.dialogVisibleEdit = false
          })
          .catch((err) => {
            return this.$message.error(err.message || '获取失败')
          })
      })
    },
    showInput(row) {
      row.inputTagVisible = true
      // 使文本框自动获取焦点
      // $nextTick 方法的作用，当页面上的元素被重新渲染之后才会指定回调函数中的代码
      // console.log(this.$refs)
      this.$nextTick((_) => {
        // console.log(this.$refs)
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm(row) {
      if (row.inputTagValue.trim().length === 0) {
        row.inputTagValue = ''
        row.inputTagVisible = false
        return
      }
      // 如果有数据就要发送请求保存数据
      
      row.values.push(row.inputTagValue.trim())
      row.inputTagValue = ''
      row.inputTagVisible = false
      this.saveProductsTypeAttr(row)
    },
    // 对 values 的操作保存到数据库
    async saveProductsTypeAttr(row) {
      await this.$http
        .put(`/productsType/${this.selectedId}/attributes/${row.type_id}`, {
          params: {
            name: row.name,
            selectedtype: this.selected_id,
            values: row.values.join(','),
          },
        })
        .then((res) => {
          res = res.data
          if (!res.code || res.code == 0)
            return this.$message.error(
              res.msg || window.defineGlobalConstData.opError
            )
          this.$message.success(window.defineGlobalConstData.opSuccess)
        })
        .catch((err) => {
          return this.$message.error(
            err.message || window.defineGlobalConstData.opError
          )
        })
    },
    // 删除对应的参数可选项
    handleClose(i, row) {
      row.values.splice(i, 1)
      this.saveProductsTypeAttr(row)
    }
  },
  computed: {
    // 判断按钮是否启用
    isBtnDisable() {
      if (this.selectedIds.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类ID
    selectedId() {
      if (this.selectedIds.length === 3) {
        return this.selectedIds[2]
      }
      return null
    },
    // 动态计算添加面板信息
    dialogTitleText() {
      if (this.activeName === '1') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
}
</style>